package cn.tedu.sp11.fallback;

import cn.tedu.sp01.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author 张琪
 * @date 2020/12/23
 * @describe
 */
@Component
public class UserFB implements FallbackProvider {
    /**
     * 返回一个serviceId, 针对指定的服务进行降级处理
     * 如果返回 * 或者 null, 那么则对所有服务都应用这个降级类
     * @return
     */
    @Override
    public String getRoute() {
        return "user-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return response();
    }

    private ClientHttpResponse response() {
        return new ClientHttpResponse() {
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type", "application/json;charset=UTF-8");
                return h;
            }

            @Override
            public InputStream getBody() throws IOException {
//                JsonResult {code: 401, msg: "调用商品服务失败", data: null}
                String json = JsonResult.err().msg("调用商品服务失败").toString();

                return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
            }

            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }


        };
    }
}
